<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="isUpdate ? '编辑' : '新增'"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { formSchema } from './ficleConfig.data';
  import { createFileConfig, getFileConfig, updateFileConfig } from '/@/api/backs/file/fileConfig';

  defineOptions({ name: 'InfraFileConfigModal' });

  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 120,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: { span: 23 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      const res = await getFileConfig({ id: data.record.id });
      setFieldsValue({ ...res, ...res.config });
    }
  });

  async function handleSubmit() {
    try {
      let values = await validate();
      let config: any = {};
      // domain id name  remark
      for (let item in values) {
        if (item !== 'id' && item !== 'name' && item !== 'remark') {
          config[item] = values[item];
        }
      }
      values.config = config;
      setModalProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        await updateFileConfig(values);
      } else {
        await createFileConfig(values);
      }
      closeModal();
      emit('success');
      createMessage.success('操作成功');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
